<template>
    <massif-layout>
        <template v-slot:left>
            <div class="massifIndex" @click="mapRef.clearSelectEditor()">
                <div class="tobBox">
                    <div class="back" @click="goBack">
                        <el-icon><ArrowLeft /></el-icon>
                        <span>返回</span>
                    </div>
                    <h5>{{farmLandId?'修改地块':'添加地块'}}</h5>
                    <div class="btnBox">
                        <el-button type="success" class="my-small-btn" @click="save">提交</el-button>
                    </div>
                </div>

                <div class="ltMainBox">
                    <el-form class="my-small-form" ref="ruleFormRef" :rules="rules" :model="formdata" label-width="80px" size="small">
                        <el-form-item label="地块名称" prop="farmLandName">
                            <el-input v-model="formdata.farmLandName" placeholder="请输入地块名称"/>
                        </el-form-item>

                        <el-form-item label="地块质地" prop="geologyId">
                            <geology-select v-model="formdata.geologyId" @change="(e)=>formdata.geologyName = e.geologyName"/>
                        </el-form-item>

                        <el-form-item label="地块分组" prop="landGroupId" class="dingwline" v-if="farmId">
                            <group-select ref="groupRef" className="small-el-input__inner" popperClass="samll-el-select-dropdown__list" v-model="formdata.landGroupId" :params="{farmId}" :defaultIndex="0" width="250px" @change="(e)=>formdata.groupName = e.groupName"/>
                            <div class="addBtn">
                                <el-button plain icon="Plus" @click="dialogFlag=true" />
                            </div>
                        </el-form-item>

                        <el-form-item label="经度" prop="locationLongitude" style="margin-bottom:7px">
                            <p style="font-size: 12px;">{{formdata.locationLongitude}}</p>
                        </el-form-item>
                        <el-form-item label="纬度" prop="locationLatitude" style="margin-bottom:7px">
                            <p style="font-size: 12px;">{{formdata.locationLatitude}}</p>
                        </el-form-item>
                        <el-form-item label="测算面积" prop="" >
                            <p style="font-size: 12px;">{{formdata.mapAreaSize}}亩</p>
                        </el-form-item>

                        <el-form-item label="地块面积" prop="areaSize">
                            <el-input v-model="formdata.areaSize" placeholder="请输入地块面积"/>
                        </el-form-item>

                        <el-form-item label="作物" prop="cropId">
                            <public-select lovCode="TANC_CROP" v-model="formdata.cropId" @change="(e)=>formdata.cropName = e.meaning"/>
                        </el-form-item>

                        <el-form-item label="所属区域" prop="locationAddress">
                            <el-input v-model="formdata.locationAddress" placeholder="请输入所属区域"/>
                        </el-form-item>
                        
                        <el-form-item label="地块权属" prop="landBelong">
                            <el-input v-model="formdata.landBelong" placeholder="请输入地块权属"/>
                        </el-form-item>

                        <el-form-item label="备注" prop="landRemark">
                            <el-input type="textarea" v-model="formdata.landRemark" :rows="8" show-word-limit maxlength="100"/>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </template>
        <tencent-map ref="mapRef" @draw_complete="drawComplete" @editor_delete="delArea" @mouse_drawing="setTips"/>
        <map-mode-control v-if="mapRef" :mapObj="mapRef"/>
        <div class="keywordBox" @click="mapRef.clearSelectEditor()">
            <map-keyword-tips @selected="getAddress" placeholder="搜索地块位置" class="mapkwStyle"/>
            <div class="fdTipsBox"><b>提示</b>：{{tipsTxt}}</div>
        </div>
        <draw-info v-if="distance" :options="{distance,area:formdata.mapAreaSize}" @btnClick="clearArea"/>
        <c-dialog v-model:show="dialogFlag" v-if="dialogFlag" title="添加地块分组" :showBtn="false" width="600px"  @close="setCurGroupSelect">
            <add-group @close="dialogFlag=false" @comfirm="setCurGroupSelect"/>
        </c-dialog>
    </massif-layout>
</template>
  
  <script setup>
  // 这里的name是为了做页面缓存，其值要跟路由里面的name值一样
  
  import { nextTick, ref, reactive,watch, onActivated,onMounted} from 'vue'
  import{useRouter} from "vue-router"

  import {addFarmLand,getLandDetail,editFarmLand,getLandList} from '@/api/plant'
  import {getFarmDetail} from '@/api/system'
  import {message} from '@/utils/element'
  import groupSelect from '@/components/custom/groupSelect.vue'
  import publicSelect from '@/components/custom/publicSelect.vue'
  import geologySelect from '@/components/custom/geologySelect.vue'
  import massifLayout from '../components/layout.vue'
  import tencentMap from '@/components/custom/tencentMap.vue'
  import { useUserStore } from '@/pinia/modules/user'
  import cDialog from '@/components/custom/cDialog.vue'
  import addGroup from './components/addGroup.vue'
  import drawInfo from './components/drawInfo.vue'
  import mapModeControl from '@/components/custom/mapModeControl.vue'
  import mapKeywordTips from '@/components/custom/mapKeywordTips.vue'

  const router = useRouter()
  const userStore = useUserStore()
  
  const mapRef = ref(null)
  const dialogFlag = ref(false)
  const farmId = ref('') // 农场id
  const farmLandId = ref('') // 地块id
  const formdata = ref({})
  const ruleFormRef = ref(null)
  const groupRef = ref(null)
  const distance = ref(0) // 路径长度（周长）
  const detail = ref({})
  const landGroupId = ref('')
  const landLists = ref([])
  let infowindowObj = '' // 地图标注对象
  let hoverInfowindowObj = ''
  let mapAreaObj='' // 保存绘制的区域对象
  const tipsTxt = ref('在地图上找到你家地块位置打点圈起来')
  

  const rules = reactive({
    farmLandName: [
        { required: true, message: '请输入地块名称', trigger: 'blur' },
        //{ min: 3, max: 50, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    geologyId:[
        { required: true, message: '请选择地块质地', trigger: 'blur' },
    ],
    // landGroupId:[
    //     { required: true, message: '请选择地块分组', trigger: 'blur' },
    // ],
    mianji:[
        { required: true, message: '请输入地块面积', trigger: 'blur' },
    ],
    areaSize:[
        { required: true, message: '请输入地块面积', trigger: 'blur' },
    ],
    cropId:[
        { required: true, message: '请选择作物', trigger: 'blur' },
    ],
    locationAddress:[
        { required: true, message: '请输入所属区域', trigger: 'blur' },
    ],
    landBelong:[
        { required: true, message: '请输入地块权属', trigger: 'blur' },
    ],
    locationLongitude:[
        { required: true, message: '请在地图上点选区域', trigger: 'blur' },
    ]
  })

  onMounted(async ()=>{
    farmId.value = router.currentRoute.value.query.farmId
    landGroupId.value = router.currentRoute.value.query.landGroupId
    farmLandId.value = router.currentRoute.value.query.farmLandId

    await nextTick()
    
    if(farmLandId.value){  // 编辑
        tipsTxt.value = '拖动白点调整地块范围'
        getLandDetail(farmLandId.value).then(res=>{
            formdata.value = res.data
            formdata.value.cropId = formdata.value.cropId.toString()
            if(res.data.landGroupId == 0){
                formdata.value.landGroupId = ''
            }

            const location = JSON.parse(res.data.location || '[]')
            mapRef.value.setCenter(res.data.locationLatitude,res.data.locationLongitude) // 设置地图中心点
            //createMapArea(location,res.data) // 绘制地图区域
            mapRef.value.setZoom(14.8)  

            //*************************************************
            // 初始化几何图形编辑
            let paths = []
            location.forEach(item =>{
                const path = new TMap.LatLng(item.lat, item.lng)
                paths.push(path)
            })
            //mapRef.value.setCenter(40.04051164600918, 116.27488518619089)
            mapRef.value.initGeometryEditor(paths)
            //**************************************
        })
    }else{
        const hcData = JSON.parse(localStorage.getItem('latestAddData') || '{}')  // 获取缓存数据
        formdata.value.landBelong = hcData.landBelong
        await get_land_list() //获取农场下的所有地块，并显示在地图上
        // 初始化鼠标绘图
        mapRef.value.drawMap()
    }
  })

  // 获取农场下的所有地块
  const get_land_list = async ()=>{
    return new Promise(async (resolve,reject) =>{
        const res = await getLandList({
            page:1,
            limit:1000000,
            farmId:farmId.value,
            landGroupId:landGroupId.value
        })
        landLists.value = res.data

        // 设置第一个为中心点
        let center = ''
        if(landLists.value && landLists.value.length>0){
            center = {
                lat:landLists.value[0].locationLatitude,
                lng:landLists.value[0].locationLongitude
            } 
            if(infowindowObj){
                infowindowObj.destroy()
            }
            createMapArea() // 在地图上创建地块区域  (把所有改农场地块画出来)
        }else{
            // 地图定位到当前农场
            const farmDetail = await getFarmDetail(farmId.value)
            center = {
                lat:farmDetail.data.locationLatitude,
                lng:farmDetail.data.locationLongitude
            } 
            mapRef.value.setMultiMarker(farmDetail.data.locationLatitude,farmDetail.data.locationLongitude)
        }
        mapRef.value.setZoom(14.8)
        center && mapRef.value.setCenter(center.lat,center.lng)
        resolve(true)
    }) 
  }

  // 在地图上创建地块区域
  const createMapArea = ()=>{
    console.log("mapAreaObj:",mapAreaObj)
    if(mapAreaObj) {
        mapAreaObj.destroy() // 先清除 
    }
    let paths = []
    landLists.value.forEach(item =>{
        const locations = JSON.parse(item.location)
        let obj = {
            farmLandId:item.farmLandId,
            itemData:item,
            path:[],
            styleId:'styel1'
        }
        locations.forEach(ele =>{
            obj.path.push(ele.lat)
            obj.path.push(ele.lng)
        })
        paths.push(obj)
    })
    //console.log("paths:",paths)
    mapAreaObj = mapRef.value.createArea(paths)
    // mapAreaObj.on("click",function(e){
    //     if(e.detail.area){ // 点击了区域
    //         goDetail(e.detail.area)
    //     }
    // })
    // mapAreaObj.on("hover",function(e){
    //     if(e.detail.area){ // 点击了区域
    //         const item = e.detail.area.itemData
    //         hoverInfowindowObj && hoverInfowindowObj.destroy()  // 销毁
    //         //if(e.detail.area.farmLandId !=dropFarmLandId.value){ // 只有不是当前选择的地块才处理
    //             hoverInfowindowObj = mapRef.value.setMarker2(item.locationLatitude,item.locationLongitude,mapShowTemplate(item,'mapMarker'))
    //         //}
    //     }else{
    //         hoverInfowindowObj && hoverInfowindowObj.destroy()  // 销毁
    //     }
    // })
  }

//   const get_Farm_Detail = ()=>{
//     return new Promise((resolve,reject) =>{
//         getFarmDetail(farmId.value).then(res =>{
//             detail.value = res.data
//             mapRef.value.setZoom(14.8)
//             mapRef.value.setCenter(res.data.locationLatitude,res.data.locationLongitude) // 设置地图中心点
//             resolve(true)
//         })
//     }) 
//   }

  const mapShowTemplate = (item,className='mapMarker') =>{
    return `<div class="${className}">
            <div class="conbox">
                <p><b>分组名称：</b>${item.groupName}</p>
                <p>${item.locationAddress}</p>
            </div>
            <div class="conbox">
                <p><b>面积：</b>${item.areaSize}</p>
                <p><b>地块权属：</b>${item.landBelong}</p>
            </div>
        </div>`
  }

  const save = async ()=>{
    await ruleFormRef.value.validate(async (valid, fields) => {
        if (valid) {
            // 缓存最后一次新增的数据，用于获取下次新增时候自动填入地块权属
            localStorage.setItem('latestAddData',JSON.stringify(formdata.value))
            let res = {}
            if(!formdata.value.landGroupId){
                formdata.value.landGroupId = null
            }
            if(farmLandId.value){
                res = await editFarmLand(formdata.value)
            }else{
                formdata.value.farmId = farmId.value
                res = await addFarmLand(formdata.value)
            }
            console.log("表单信息：",formdata.value)
            
            if(res.code ==0 || res.success){
                message('数据提交成功',2)
                goBack()
            }else{
                message(res.message,3)
            }
        } else {
            console.log('error submit!', fields)
        }
    })
  }

  const drawComplete = async (data)=>{
    console.log("回调获得绘制信息：",data)
    if(data.type ==1){ // 创建完成回调的
        tipsTxt.value = '拖动白点调整地块范围'
    }else if(data.type ==2){ // 编辑回调的
        tipsTxt.value = '点击左侧“提交”按钮创建地块'
    }
   // console.log(data.paths[0])
    formdata.value.mapAreaSize = (data.area *0.0015).toFixed(2) // 转化为亩
    formdata.value.location = JSON.stringify(data.paths)   // 保存所有坐标
    distance.value = data.distance  // 周长
    // 获取第一个
    formdata.value.locationLatitude = data.paths[0].lat
    formdata.value.locationLongitude = data.paths[0].lng

    // 根据经纬度获取地址
    const res =await mapRef.value.latLng_convert_to_address(formdata.value.locationLatitude,formdata.value.locationLongitude)
    //console.log("地址：",res)
    formdata.value.locationAddress = res.formatted_addresses.standard_address +' '+ res.formatted_addresses.recommend 
  }

  const setCurGroupSelect = async (item)=>{
    await groupRef.value.getTableData() // 刷新
    if(item && item.landGroupId){
        formdata.value.landGroupId = item.landGroupId
        formdata.value.groupName = item.groupName
    } 
  }

  const delArea = ()=>{
    formdata.value.locationLatitude = ''
    formdata.value.locationLongitude = ''
    formdata.value.mapAreaSize = ''
    formdata.value.location=''
    formdata.value.locationAddress = ''
    distance.value = 0
    tipsTxt.value = '在地图上找到你家地块位置打点圈起来'
    // 重新设置鼠标绘图
    mapRef.value.drawMap()
  }

  const getAddress = (detail)=>{
    console.log("选择===：",detail)
    // 设置中心点
    mapRef.value.setCenter(detail.location.lat,detail.location.lng)
    // 标记
    mapRef.value.removeAllMarker()
    mapRef.value.setMultiMarker(detail.location.lat,detail.location.lng)
  }

  const clearArea = ()=>{
    mapRef.value.destroyEditor()
    delArea()
  }

  // 鼠标绘制中回调函数
  const setTips = (o)=>{
    if(!o.geometry){ // 打1个点时
        tipsTxt.value = '继续打点，把地块圈起来，双击完成圈地'
    }
    // else{
    //     if(o.geometry.paths.length == 3){ // 打2个点时
    //         tipsTxt.value = '拖动白点调整地块边界把地块圈起来'
    //     }else if(o.geometry.paths.length > 3){ // 打3个点及以上
    //         tipsTxt.value = '画完地块，点击左侧“提交”地块'
    //     }
    // }
  }
  
  const goBack = ()=>{
    router.back(-1)
  }
  
  </script>
  
  <style lang="scss" scoped>
    .massifIndex{
        box-sizing: border-box;
        display: flex;
        flex-flow: column;
        height: 100%;
        padding: 10px 0;
        overflow: hidden;
        .tobBox{
            position: relative;
            z-index: 10;
            font-size: 12px;
            box-sizing: border-box;
            align-items: center;
            height: 30px;
            line-height: 29px;
            padding: 0 10px;
            border-bottom: 1px solid #e9e7e7;
            h5{
                font-size: 14px;
                font-weight: normal;
                text-align: center;
            }
            .back{
                display: flex;
                align-items: center;
                position: absolute;
                left: 10px;
                top: 0;
                z-index: 10;
                height: 100%;
                line-height: 29px;
                font-size: 12px;
                cursor: pointer;
                &:hover{
                    color: #48b27a;
                }
                span{
                    flex-shrink: 0;
                }
            }
            .btnBox{
                display: flex;
                align-items: center;
                position: absolute;
                right: 10px;
                top: 0;
                z-index: 10;
                height: 100%;
                i{
                    font-size: 18px;
                    cursor: pointer;
                    &:hover{
                        color: #48b27a;
                    }
                    &+i{
                        margin-left:10px ;
                    }
                }
            }
        }
        .tabBox{
            display: flex;
            box-sizing: border-box;
            align-items: center;
            height: 40px;
            padding: 0 15px;
            overflow: hidden;
        }
        
        .ltMainBox{
            box-sizing: border-box;
            //flex: 1;
            height: calc(100vh - 134px);
            flex-shrink: 0;
            width: 100%;
            padding: 10px;
            overflow: hidden;
            overflow-y: auto;
        }
        .bottom-page{
            box-sizing: border-box;
            flex-shrink: 0;
            height: 30px;
            padding: 0 15px;
        }
    }
    .keywordBox{
        position: absolute;
        z-index: 1000;
        left: 50px;
        top: 20px;
        //transform: translateX(-50%);
        //-webkit-transition: translateX(-50%);
        .fdTipsBox{
            position: absolute;
            z-index: 1000;
            left: 0;
            top: 30px;
            box-sizing: border-box;
            min-width: 100%;
            white-space: nowrap;
            background: #e8a411;
            line-height: 24px;
            padding: 0 10px;
        }
    }
  </style>
  <style lang="scss">
  .tabBox{
    .el-tabs__header {
        margin: 0;
    }
    .el-tabs__nav{
        display: flex;
        width: 100%;
        .el-tabs__item{
            flex: 1;
            text-align: center;
            font-size: 12px;
        }
    }
  }
  .dingwline{
    position: relative;
    z-index: 10;
    .addBtn{
        position: absolute;
        z-index: 10;
        height: 30px;
        right: 0;
        top: 0;
        .el-button{
            box-sizing: border-box;
            height: 30px !important;
            min-height: 30px;
            padding: 0 10px;
        }
    }
  }
  </style>
  